<!--  -->
<template>
  <div class="page-nav-list">
    <el-scrollbar style="height:100%;">
    <div class="nav-list">
      <el-tree v-loading="pageLoading" ref="treePage" :data="pageData" :props="defaultProps" default-expand-all
        icon-class=" " :indent="0">
        <div class="custom-tree-node pnl-item" slot-scope="{ node, data }">
          <div class="pnl-left">
            <div class="label-name">{{ node.label }} <i class="el-icon-edit"
                :style="{ 'visibility': data.showEditor ? 'visible' : 'hidden' }" @click.stop="editor(data)" /></div>
            <div class="label-edit" style="display:none">
              <el-form :model="node">
                <input type="text" v-model="node.label" />
                <i class="el-icon-check" @click.stop="" />
              </el-form>
            </div>
          </div>
          <div class="pnl-opt">
            <span class="ptype">{{data.pType}}</span>
            <span class="design-btn" :style="{ 'visibility': data.showDesign ? 'visible' : 'hidden' }"
              @click.stop="design(data)">设计</span>
          </div>
        </div>
      </el-tree>
    </div>
    </el-scrollbar>
  </div>
</template>

<script>
// 公共方法
import * as DesignFunctions from '@/core/DesignFunctions.js'
import * as WindowType from '@/config/windowtype.js'
import * as PubsubType from '@/config/pubsubtype.js'
import VueFunctions from '@/core/VueFunctions.js'
import BackendjsFunctions from '@/core/BackendjsFunctions.js'
import { mapGetters } from 'vuex'
import PubSub from 'pubsub-js'
export default {
  created () {
    this.getData()
    PubSub.subscribe(PubsubType.PUBSUB_REFRENCE_NAVIGATION_INFO, (event, data) => {
      this.getData(data)
    })
    PubSub.subscribe(PubsubType.PUBSUB_CHOOSE_NAVIGATION_PAGE_ACTION, (event, data) => {
      this.design(data)
    })

    // 点击导航触发的页面跳转动作
    VueFunctions.method(WindowType.DESIGN_PAGE_GOTO_WITH_HREF, (href, pageid) => {
      let listNavigation = BackendjsFunctions.getListNavigationData()
      const recursion = (list, pid) => {
        let result = null
        for (let i in list) {
          let item = list[i]
          if (parseInt(item.pageId) === parseInt(pid)) {
            result = item
            break
          }
          if (item.children) {
            result = recursion(item.children, pid)
            if (result) {
              break
            }
          }
        }
        return result
      }
      let item = recursion(listNavigation, pageid)
      if (!item) {
        this.$message.error('未能找到 Navigation 数据，请连续管理员！')
        return
      }
      if (item.pageType === 'external_link') {
        this.$message.error('外链接无法被编辑！')
        return
      }
      let src = DesignFunctions.getDesignPath(this.$store.state.host.id, this.$store.state.site.site.id, href)
      this.$store.dispatch('designSetIframeSrc', src)
    })
  },
  computed: {
    ...mapGetters([
      'currentIframeSrc'
    ])
  },
  props: {
    editorPageName: {
      type: Function
    },
    closeDialog: {
      type: Function
    },
    openCenter: {
      type: Function
    }
  },
  data () {
    return {
      // loading
      pageLoading: true,
      // 请求获取的response数据
      data: [],
      // 转化成表格后的数据
      pageData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 当前页面的id
      currentPageId: -1,
      // 当前系统的id
      currentSystemId: -1,
      // 当前分类的id
      currentCategoryId: -1,
      // 当前详情的id
      currentItemId: -1
    }
  },
  methods: {
    getData (callback) {
      this.$post('/page/infos').then(response => {
        this.pageLoading = false
        if (response && response.pages) {
          this.data = initData(response.pages)
          this.pageData = initPageData(this.data)
          // 找到当前的地址数据
          let uri = DesignFunctions.getUriByDesign(this.$store.state.host.id, this.$store.state.site.site.id, this.currentIframeSrc)
          if (uri.indexOf('?') !== -1) {
            let uriArray = uri.split('?')
            if (uriArray && uriArray[0]) {
              uri = uriArray[0]
            }
          }
          let page = null
          if (uri === '/index.html') {
            page = this.data[0]
          } else {
            // page = this.data.find(element => {
            //   return element.link === uri
            // })
            for (let i in this.data) {
              if (this.data[i].link === uri) {
                page = this.data[i]
              } else if (this.data[i].children && this.data[i].children.length > 0) {
                for (let j in this.data[i].children) {
                  if (this.data[i].children[j].link === uri) {
                    page = this.data[i].children[j]
                  } else if (this.data[i].children[j].children && this.data[i].children[j].children.length > 0) {
                    for (let k in this.data[i].children[j].children) {
                      if (this.data[i].children[j].children[k].link === uri) {
                        page = this.data[i].children[j].children[k]
                      }
                    }
                  }
                }
              }
            }
          }
          if (page) {
            this.currentPageId = page.pageId
            this.currentSystemId = page.systemId
            this.currentCategoryId = page.categoryId
            this.currentItemId = page.itemId
          } else {
            console.warn('通过 uri 未能找到其对应的当前页面', uri, this.data)
          }
        } else {
          this.data = []
          this.pageData = []
        }
        if (typeof callback === 'function') {
          callback()
        }
        this.$nextTick(() => {
          this.openCenter()
        })
      })
    },
    design (item) {
      // 通过找到 data 中的对应的数据，构建渲染页面的url
      // let page = this.data.find(element => {
      //   return element.pageId === item.id
      // })
      // 优化
      // let page = []
      // let dataN = this.data
      // for (let i in dataN) {
      //   if (dataN[i].pageId === item.id) {
      //     page.push(dataN[i])
      //   } else if (dataN[i].children && dataN[i].children.length > 0) {
      //     for (let j in dataN[i].children) {
      //       if (dataN[i].children[j].pageId === item.id) {
      //         page.push(dataN[i].children[j])
      //       } else if (dataN[i].children[j].children && dataN[i].children[j].children.length > 0) {
      //         for (let k in dataN[i].children[j].children) {
      //           if (dataN[i].children[j].children[k].pageId === item.id) {
      //             page.push(dataN[i].children[j].children[k])
      //           }
      //         }
      //       }
      //     }
      //   }
      // }
      // if (!page || page.length < 1) {
      //   return
      // }
      // let src = DesignFunctions.getDesignPath(this.$store.state.host.id, this.$store.state.site.site.id, page[0].link)
      if (!item.link) {
        return
      }
      let src = DesignFunctions.getDesignPath(this.$store.state.host.id, this.$store.state.site.site.id, item.link)
      if (src === this.currentIframeSrc) {
        src = src + '?' + new Date().getTime()
      }
      this.$store.dispatch('designSetIframeSrc', src)
      this.closeDialog()
    },
    editor (data) {
      // 这里编辑只能针对名称进行编辑
      this.editorPageName(data.id)
    }
  },
  components: {
    // EditorPageName
  }
}
/**
 * 构建初始化页面data的数据
 */
function initData (response) {
  if (!response || response.length < 1) {
    return []
  }
  let result = []
  for (let i in response) {
    let item = response[i]
    if (item.length > 0) {
      for (let j in item) {
        let ite = item[j]
        let pageType = 'custom'
        if (ite.type === 1) {
          pageType = 'custom'
        } else if (ite.type === 3) {
          pageType = 'external_link'
        } else if (ite.pageType === 4) {
          pageType = 'inside_link'
        } else if (ite.pageType === 2) {
          pageType = 'list'
        }
        let link = ''
        if (ite.type === 3 || ite.type === 4) {
          link = ite.url
        } else {
          link = '/' + ite.rewrite + '.html'
        }
        let systemId = -1
        if (ite.systemId) {
          systemId = ite.systemId
        }
        let element = {
          id: ite.pageId,
          index: 0,
          itemId: -1,
          link: link,
          pageId: ite.id,
          pageType: pageType,
          systemId: systemId,
          target: ite.target,
          text: ite.name,
          title: ite.name,
          status: ite.status,
          hide: ite.hide,
          children: []
        }
        if (parseInt(i) > 0 && result.length > 0) {
          result.forEach(el => {
            if (ite.parentId === el.pageId) {
              element.index = el.index + 1
              el.children.push(element)
            } else if (el.children.length > 0) {
              el.children.forEach(ele => {
                if (ite.parentId === ele.pageId) {
                  element.index = ele.index + 1
                  ele.children.push(element)
                }
              })
            }
          })
        } else {
          result.push(element)
        }
      }
    }
  }
  return result
}

/**
 * 构建初始化tree的数据
 */
function initPageData (response) {
  if (!response || response.length < 1) {
    return []
  }
  let result = []
  for (let i in response) {
    let item = response[i]
    let showDesign = true
    let showEditor = true
    let pType = '未定义'
    if (item.pageType === 'custom') {
      pType = '普通'
    } else if (item.pageType === 'external_link') {
      pType = '外链'
      showDesign = false
    } else if (item.pageType === 'inside_link') {
      pType = '内链'
      showDesign = false
    } else if (item.pageType === 'list') {
      pType = '系统'
      if (item.categoryId > 0) {
        showDesign = false
        showEditor = false
        pType = '分类'
      }
    }
    let element = {
      id: item.pageId,
      systemId: item.systemId,
      categoryId: item.categoryId,
      itemId: item.itemId,
      pType: pType,
      showDesign: showDesign,
      showEditor: showEditor,
      label: item.text,
      children: initPageData(item.children),
      link: item.link
    }
    if (!(item.pageType === 'list' && item.categoryId > 0) && item.status > 0) {
      result.push(element)
    }
  }
  return result
}
</script>

<style scoped lang="scss">
.page-nav-list {
  height: calc(100vh - 140px);
}
.page-nav-list /deep/ {
  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
  .is-horizontal{
    display: none;
  }
}
.nav-list {
  color: #333;
  padding: 0 20px;
  /deep/ .el-tree__empty-block {
    height:300px
  }
  /deep/ .el-tree-node__content {
    height: auto;
    background: #fbfbfb;
    padding: 0 15px;
    margin-bottom: 2px;
  }
  /deep/ .el-tree-node__children {
    padding-left: 25px;
  }
  .pnl-item {
    display: flex;
    width: 100%;
    align-content: center;
    align-items: center;
    cursor: default;
    .pnl-left {
      flex: auto;
      .label-name {
        padding: 12px 0 12px 5px;
        white-space: normal;
        i {
          font-size: 18px;
          cursor: pointer;
          &:hover {
            color: #258ffb;
          }
        }
      }
    }
    .pnl-opt {
      display: flex;
      flex-shrink: 0;
      align-content: center;
      align-items: center;
      .ptype {
        color: #999;
        margin: 0 10px;
        font-size: 13px;
      }
      .design-btn {
        cursor: pointer;
        &:hover {
          color: #258ffb;
        }
      }
    }
  }
}
</style>
